package com.dexilaonian.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dexilaonian.R;
import com.dexilaonian.ui.BaseActivity;
import com.dexilaonian.utils.Constant;
import com.dexilaonian.view.SecurityCodeView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class Register_smsActivity extends BaseActivity implements SecurityCodeView.InputCompleteListener {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title_top)
    TextView titleTop;
    @Bind(R.id.et)
    TextView ett;
    @Bind(R.id.base_login)
    TextView baseLogin;
    @Bind(R.id.rl_title)
    RelativeLayout rlTitle;
    @Bind(R.id.sms_phone)
    TextView smsPhone;
    @Bind(R.id.btn_register_sms)
    Button btnReg;
    @Bind(R.id.register_sms_time)
    TextView registerSmS;
    @Bind(R.id.edit_security_code)
    SecurityCodeView editSecurityCode;
    private String send_sms_url;
    private String str_phone;
    private String ett1;
    private String changecc;
    private String str_phone_find;
    int count=0;
    String phone = "";
    private TimeCount time;

    @Override
    public int getLayoutID() {
        return R.layout.activity_register_sms;
    }
    @Override
    public void initView() {
        send_sms_url = Constant.base_url+"/verify/checkSmsVerify";
        time = new TimeCount(60000, 1000);
        time.start();
    }
    @Override
    protected void initData() {}
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        Intent intent = getIntent();
        str_phone = intent.getStringExtra("str_phone");
        str_phone_find = intent.getStringExtra("str_phone_find");
        String change = intent.getStringExtra("Change1");
        if (!TextUtils.isEmpty(str_phone)) {
            smsPhone.setText(str_phone);
            count = 0;
            phone=str_phone;
        }
        if (!TextUtils.isEmpty(change)) {
            smsPhone.setText(change);
            count = 1;
            phone=change;
        }
        if (!TextUtils.isEmpty(str_phone_find)) {
            smsPhone.setText(str_phone_find);
            count =1;
            phone=str_phone_find;
        }
        btnReg.setClickable(false);
        editSecurityCode.setInputCompleteListener(this);
        editSecurityCode.requestFocus();
    }

    @OnClick({R.id.register_sms_time,R.id.back, R.id.base_login, R.id.btn_register_sms})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.register_sms_time:
                sendPhone(phone);
                break;
            case R.id.btn_register_sms:
                register_sms(phone);
                break;
            case R.id.base_login:
                startActivity(new Intent(Register_smsActivity.this, LoginActivity.class));
                finish();
                break;
        }
    }

    private void register_sms(String phone3) {
        showProgressBar(true);
        OkHttpUtils.post().
                url(send_sms_url)
                .addParams("phone", phone3)
                .addParams("code", editSecurityCode.getEditContent().toString().trim())
                        .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("xuException", e.getMessage());
                showToast(e.getMessage());
                showProgressBar(false);
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e("xuxuxsms", response);
                showProgressBar(false);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int data = Integer.parseInt(jsonObject.optString("status"));
                    Log.e("data", response);
                    if (data == 1) {
                        showToast("手机号格式不正确");
                        return;
                    }
                    if (data == 3) {
                        showToast("验证码格式不正确");
                        return;
                    }
                    if (data == 5) {
                        showToast("验证码过期（时间超过10分钟）");
                        return;
                    }
                    if (data == 8) {
                        showToast("验证码错误");
                        return;
                    }
                    if (data == 0) {
                        Intent intent = new Intent(Register_smsActivity.this, Input_NewPwdActivity.class);
                        intent.putExtra("sms_phone", Register_smsActivity.this.phone);
                        intent.putExtra("count", count+"");

                        startActivity(intent);
                    } else {
                        showToast("验证失败");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void inputComplete() {
        btnReg.setBackground(getResources().getDrawable(R.drawable.button));
        btnReg.setClickable(true);
    }

    @Override
    public void deleteContent(boolean isDelete) {
        btnReg.setBackground(getResources().getDrawable(R.drawable.graybutton));
        btnReg.setClickable(false);
    }
    /**
     * 计时器
     */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {
            //计时完毕时触发
            registerSmS.setText("重发");
            registerSmS.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {//计时过程显示
            if (registerSmS!=null) {
                registerSmS.setText("接收短信大约需要"+millisUntilFinished / 1000 + "秒");
            }
        }
    }
    private void sendPhone(String phone0) {
        showProgressBar(true);
        String phone_url = Constant.base_url + "/verify/sentSmsVerify";
        OkHttpUtils.post().url(phone_url).addParams("phone",phone0).addParams("type",count+"").build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showToast(e.getMessage());
                showProgressBar(false);
            }
            @Override
            public void onResponse(String response, int id) {
                showProgressBar(false);
                Log.e("TTTforget2222", response);
                try {
                    JSONObject object = new JSONObject(response);
                    int status = Integer.parseInt(object.optString("status"));
                    if (status == 6) {
                        showToast("单手机号单日发送短信超10条");
                        return;
                    }
                    if (status == 7) {
                        showToast("单手机号短信发送时间间隔少于1分钟");
                    }
                    if (status==0) {
                        time.start();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }
}
